package devicelogic

import (
	"context"

	productlogic "go-zero-admin/apps/modules/iot/cmd/rpc/internal/logic/product"
	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetDeviceOneLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	getProductOneLogic *productlogic.GetProductOneLogic
}

func NewGetDeviceOneLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDeviceOneLogic {
	return &GetDeviceOneLogic{
		ctx:                ctx,
		svcCtx:             svcCtx,
		Logger:             logx.WithContext(ctx),
		getProductOneLogic: productlogic.NewGetProductOneLogic(ctx, svcCtx),
	}
}

func (l *GetDeviceOneLogic) GetDeviceOne(in *iotpb.GetDeviceOneReq) (*iotpb.GetDeviceOneResp, error) {
	one, err := l.svcCtx.IotDeviceModel.FindOne(l.ctx, in.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("get device one"), err, in)
	}

	// 判断一下，该设备是否有自定义的物模型，如何没有，则调用自己产品的物模型进行展示
	if one.Metadata == "" {
		productOne, err := l.svcCtx.IotProductModel.FindOne(l.ctx, one.ProductId)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
				tool.GetErrMsgFormat("get device one"), err, in)
		}
		one.Metadata = productOne.Metadata
	}

	// 转换数据
	var data iotpb.IotDevice
	_ = copier.Copy(&data, one)

	return &iotpb.GetDeviceOneResp{One: &data}, nil
}
